package com.trace.util;

import com.trace.pool.ThreadPool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * Created by denglw on 2020/1/9.<br/>
 * Desc: 闭锁:
* CountDownLatch是一个同步辅助类，它允许一个或多个线程一直等待直到其他线程执行完毕才开始执行。
 * 用给定的计数初始化CountDownLatch，其含义是要被等待执行完的线程个数。
 * 每次调用CountDown()，计数减1
 * 主程序执行到await()函数会阻塞等待线程的执行，直到计数为0
 *
 */
public class LatchTest {

    private static final int RUNNER_COUNT = 10;

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch begin = new CountDownLatch(1);
        final CountDownLatch end = new CountDownLatch(RUNNER_COUNT);
        final ExecutorService exec = ThreadPool.pool();

        for (int i = 0; i < RUNNER_COUNT; i++) {
            final int no = i + 1;
            Runnable run = () -> {
                try {
                    begin.await();
                    Thread.sleep(1000);
                    System.out.println("No." + no + " arrived");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    end.countDown();
                }
            };
            exec.submit(run);
        }
        System.out.println("Game Start ...");
        begin.countDown();
        end.await();
        System.out.println("Game Over.");
        exec.shutdown();
    }
}
